# -*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<komazhang@foxmail.com>
" Date : 2015-11-06
"""
from __future__ import unicode_literals
import threading
import time

from flask import Flask
from flask import request
from flask import jsonify
from flask import g



app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
#app.config['SERVER_NAME'] ='api.iou.ink'


Threadflag = True
commandJSON = False
ESPcallback=False
ESP_Online =0



@app.route("/<data>", methods=["GET", "POST"])
def rec_cmd(data):
    global commandJSON,ESPcallback,ESP_Online,Threadflag
    print("request =-> "+data)
    info = request.args.get('info', default = '', type = str)
    cmd = request.args.get('cmd', default = '', type = str)


    if data == "get_json":
        ESP_Online=10
        ESPcallback = False
        if Threadflag:
            t1 = threading.Thread(target=CountOnline)
            t1.start()
        if commandJSON:
            # run command
            tempJson=commandJSON
            commandJSON = False
            return jsonify(tempJson), 200
        else:
            jsondata = {"info": "everything_OK", "type": "success"}
            return jsonify(jsondata), 200
            # return jsonify({"info": "opening led","cmd": "pin = machine.Pin(2, machine.Pin.OUT);pin.on()","type":"cmd"}), 200
    elif data == "send_cmd":
        commandJSON = {"info": info, "cmd": cmd, "type": "cmd"}
        #jsondata={"info": "closing led","cmd": "pin = machine.Pin(2, machine.Pin.OUT);pin.off()","type":"cmd"}
        timeout=0
        while True:
            try:
                if ESPcallback:
                    if ESPcallback =="success":
                        ESPcallback =False
                        return jsonify({"info": "执行成功","type":"success"}), 200
                    elif ESPcallback =="error":
                        ESPcallback =False
                        return jsonify({"info": "执行出错","type":"error"}), 200
                    else:
                        ESPcallback =False
                        return jsonify({"info": "未知错误","type":"error"}), 200
                elif timeout<8:
                    timeout+=1
                else:
                    return jsonify({"info": "执行超时", "type": "error"}), 200

                print("wating for callback...")
            except(TimeoutError):
                print("timeout_error!")
            time.sleep(1)
    elif data == "check_state":
        if ESP_Online>0:
            return jsonify({"info": "EPS在线", "type": "success"}), 200
        else:
            return jsonify({"info": "EPS离线", "type": "error"}), 200


@app.route("/espCallback", methods=["GET", "POST"])
def esp_call():
    global ESPcallback
    type = request.args.get('type', default = '', type = str)
    print("callback =-> "+type)
    if type =="success":
        ESPcallback = "success"
    elif type =="error":
        ESPcallback = "error"
    return jsonify({"info": "callBack "+type+" received", "type": "success"}), 200

@app.route('/favicon.ico')
def favicon():
    return app.send_static_file('https://xn--15t.top/img/favicon.ico')

@app.route('/')
def index():
    return app.send_static_file('index.html')


def CountOnline():
    global Threadflag,ESP_Online
    Threadflag=False
    print("  Start Counting ="+str(ESP_Online))
    while ESP_Online > 0:
        ESP_Online = ESP_Online - 1
        print("ESP_Online", ESP_Online)
        time.sleep(1)
    if ESP_Online == 0:
        Threadflag =True
        print("count==0")

def callback(data):
    g.return_data=data


def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res



if __name__ == "__main__":

    app.run(
        host="127.0.0.1",
        #155.94.158.151
        port=int("8032"),
        debug=True
    )
